<?php

/*
 * user Controller class
 * PHP versions 5.1.4
 * @filesource
 * @author   Manisha/Reetu
 * @version 0.0.1 
 *   - Initial release 
 */

class UsersController extends AppController {

    //var $name = 'Users';
    //var $helpers = array('html', 'text', 'javascript', 'ajax', 'Session', 'utility', 'pagination', 'DateFormat', 'validation');
    //public $components = array('Session', 'RequestHandler', 'Cookie', 'Email', 'Paypal', 'Language','Upload');
    //public $components = array('Paginator');

    /* __________________________________________________________
     * @Method      :beforeFilter
     * @Description :to set up the Auth component
     * @access      :null
     * @param      :null
     * @return     :null
     */
    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('registration', 'forgetPassword', 'resetPassword', 'index', 'loggedbyother', 'login', 'admin_forgetPassword', 'admin_resetPassword', 'changeSiteLanguage', 'admin_changeSiteLanguage', 'continueLogin');
    }

    /* __________________________________________________________
     * @Method      :Index
     * @Description :To show the home page
     * @access      :null
     * @param      :null
     * @return     :null
     */

    function index() {
        $this->layout = 'index';
        if (count($this->Auth->User()) != 0) {
            $userDetail = $this->Auth->User();
            $this->set("userDetail", $userDetail);
        }
    }

    /* __________________________________________________________
     * @Method      :changeSiteLanguage
     * @Description :Change the site language
     * @access      :null
     * @param      :$lang
     * @return     :null
     */

    function changeSiteLanguage($lang = null) {
        $this->change($lang);
        $this->redirect($this->referer(null, true));
    }
    
    /* __________________________________________________________
     * @Method      :changeSiteLanguage
     * @Description :Change the site language
     * @access      :null
     * @param      :$lang
     * @return     :null
     */
    function change($lang = '') {		
		if (!empty($lang)) {		
		    $this->Session->write('Config.language', $lang);
		    $this->Cookie->write('lang', $lang, null, '+350 day');
		}
	} 

    /*
     * @Method      :forgetPassword
     * @Description :Through this function user can retain password by
      resetting his old password through email
     * @access      :null
     * @param       :null
     * @return      :null
     */

    function forgetPassword() {
        $this->layout = 'usermainsite';
        if (!empty($this->request->data)) {
            $this->User->set($this->request->data);
            if ($this->User->validates()) {
                $userDetail = $this->User->isValidEmail($this->request->data);
                if ($userDetail != 0) {
                    if ($userDetail['active_status'] != 1) {
                        $err['notactivated'] = __("ACOUNT_NOT_ACTIVATED", true);
                        $this->set('msgs', $err);
                    } elseif ($userDetail['confirm_status'] != 1) {
                        $err['notconfirmed'] = __("ACOUNT_NOT_CONFIRMED", true);
                        $this->set('msgs', $err);
                    } else {
                        $activationNumber = $this->generateRandStr(32);
                        $userId = $userDetail['id'];
                        $email = $userDetail['email'];

                        $this->Email->from = 'admin@elaw.com';

                        $this->set('Email', $email);
                        $this->set('Username', $userDetail['first_name']);

                        $userDetailUpdate = $this->User->UpdateResetPass($userId, $activationNumber);
                        if ($userDetailUpdate) {
                            $link = "https://" . $_SERVER["HTTP_HOST"] . "/users/resetPassword/" . $userId . "/" . $activationNumber;
                            $activationLink = "<a href=" . $link . ">Click here</a>";

                            $this->set('activationLink', $activationLink);
                            $this->Email->to = $userDetail['email'];
                            $this->Email->sendAs = 'both';

                            App::Import("Model", "EmailTemplate");
                            $EmailModel = new EmailTemplate();

                            $emailDetail = $EmailModel->find("first", array('conditions' => array("code='FP0001'", "status='1'"), 'fields' => array('EmailTemplate.content', 'EmailTemplate.subject')));

                            $emailContent = $emailDetail['EmailTemplate']['content'];
                            $originalContent = array("{FIRST_NAME}", "{LAST_NAME}", "{ACTIVATION_LINK}"); //These are the variables that are used in email templates
                            $userContent = array($userDetail['first_name'], $userDetail['last_name'], $activationLink); //user details variables
                            $finalEmail = str_replace($originalContent, $userContent, $emailContent); //replacing the variables with user variables
                            $this->Email->text_body = $finalEmail;
                            $this->Email->subject = $emailDetail['EmailTemplate']['subject'];

                            if ($this->Email->send()) {
                                $this->request->data['User']['id'] = $userId;
                                $this->request->data['User']['password_reset_link'] = date("Y-m-d");

                                $this->User->Save($this->request->data['User']);
                                $msg = __("PASSWORD_RECOVERY_LINK", true);
                                $cls = "totalSuccess";
                            } else {
                                $msg = "Cannot send email please check the administrator settings";
                                $cls = "totalErrors";
                            }
                            $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');
                        }

                        $this->redirect(array('action' => 'login'));
                    }
                } else {
                    $err['wrongUsername'] = __("WRONG_USERNAME", true);
                    $this->set('msgs', $err);
                }
            } else {
                $msgs = $this->User->invalidFields();
                $this->request->data['email'] = '';
                $this->set('msgs', $msgs);
            }
        }
    }

    /*
     * @Method      :resetPassword
     * @Description :Through this function user can reset his old password t
     * @access      :null
     * @param       :$userId,$activationLink
     * @return      :null
     */

    function resetPassword($userId = null, $activationLink = null) {

        $this->layout = 'usermainsite';
        $this->set("userId", $userId);
        $this->set("activationLink", $activationLink);

        if (!empty($this->request->data)) {
            //calling login validation validLogin() in model 
            if ($this->User->validates()) {
                $userDetail = $this->User->checkValidUser($this->request->data['User']['userId']);
                if (is_array($userDetail)) {
                    $this->request->data1['User']['id'] = $userDetail['id'];
                    $this->request->data1['User']['password'] = Security::hash($this->request->data['User']['resetpwd'], null, true);
                    $this->User->Save($this->request->data1);
                    $msg = __("PASSWORD_RESET", true);
                    $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                    $this->redirect(array('controller' => 'users', 'action' => 'login'));
                } else {
                    $err['loginFailed'] = __("PASSWORD_RESET_ERROR", true);
                    $this->set('msgs', $err);
                }
            } else {

                $this->request->data['User']['resetpwd'] = '';
                $this->request->data['User']['con_pwd'] = '';
                $this->set('msgs', $msgs);
            }
        } else {
            if ($this->User->validatesResetLink($activationLink, $userId)) {
                //Do nothing
            } else {
                $msg = __("PASSWORD_RESET_EXP", true);
                $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
                $this->redirect(array('controller' => 'users', 'action' => 'login'));
            }
        }
    }

    /*
     * @Method      :generateRandStr
     * @Description :Generate Random String
     * @access      :null
     * @param       :null
     * @return      :null
     */

    function generateRandStr($length) {
        $randstr = "";
        for ($i = 0; $i < $length; $i++) {
            $randnum = mt_rand(0, 61);
            if ($randnum < 10) {
                $randstr .= chr($randnum + 48);
            } else if ($randnum < 36) {
                $randstr .= chr($randnum + 55);
            } else {
                $randstr .= chr($randnum + 61);
            }
        }
        return $randstr;
    }

    public function login() {
        $this->layout = 'default_inner';
        if ($this->request->is('post')) {
            if ($this->checkLogin($this->request['data']['User']['email'])) {
                if ($this->Auth->login()) {
                    $userId = $this->Auth->User("id");
                    //-------to track multi login ---------------
                    $logId = $this->saveLogEntry($userId);
                    $this->Session->write('Auth.User.LogId', $logId);
                    
                    $this->saveActionLog('login', 'Logeed in to system');
                    return $this->redirect($this->Auth->loginRedirect['action']);
                }
                $loginFailedMsg = __("LOGIN_FAILED", true);
                $this->Session->setFlash('<div class="totalErrors">' . $loginFailedMsg . '</div>');
            } else {
                $this->Session->write('userData', $this->request->data);
                $this->redirect(array('controller' => 'users', 'action' => 'loggedbyother'));
            }
        }
        if ($this->Auth->User('id')) {
            return $this->redirect($this->Auth->loginRedirect['action']);
        }
    }
    
    /**
     * @method: loggedbyother
     * @purpose: tell user that he is also logged in by some other pc
     * @param none
     * @return void
     * */
    function loggedbyother() {
        //pr($this->Session->read());
    }
    
    
    /**
     * @method: continueLogin
     * @purpose: allow user to login by current pc.. if user click continue
     * @param none
     * @return void
     * */
    function continueLogin() {

        $userData = $this->Session->read('userData');
        $userDetails = $this->User->find('first', array(
                            'conditions' => array('User.email' => $userData['User']['email'])
                        ));

        $userId = $userDetails['User']['id'];
        $this->Session->write('Auth.User.id', $userDetails['User']['id']);
        $this->deleteExistSession();
        
        $data = array();
        $data['User']['password'] = $userData['User']['password'];
        $data['User']['email'] = $userData['User']['email'];

        $this->Auth->login($data);
        $this->Session->write('Auth.User.id', $userId);

        //-------to track multi login ---------------
        $logId = $this->saveLogEntry($userId);
        $this->Session->write('Auth.User.LogId', $logId);
        return $this->redirect($this->Auth->loginRedirect['action']);
    }
    
    /**
     * @method: terminateLogin
     * @purpose: allow user to retain earlier session and moved to logout page
     * @param none
     * @return void
     * */
    function terminateLogin() {
        $this->logout();
    }
    
    /**
     * @method: deleteExistSession
     * @purpose: delete user log entries from database only, not destroy session 
     * @param none
     * @return void
     * */
    function deleteExistSession() {
        $userId = $this->Session->read('Auth.User.id');
        App::import('Model', 'Log');
        $this->Log = new Log();
        $this->Log->deleteAll(array('Log.user_id' => $userId), false);
    }
    
    public function logout() {
        $this->deleteExistSession();
        return $this->redirect($this->Auth->logout());
    }

    /*
     * @Method      :udateStaffData
     * @Description :This function will
     * @access      :null
     * @param       :null
     * @return      :null
     */

    function updateStaffData($userData) {
        App::Import("Model", "Staff");
        $staffModel = new Staff();
        $fetchStaffDetail = $staffModel->find("first", array('conditions' => array('Staff.user_id=' . $userData['User']['id'])));

        if (is_array($fetchStaffDetail) && count($fetchStaffDetail)) {
            $userData['Staff']['id'] = $fetchStaffDetail['Staff']['id'];
        }
        $userData['Staff']['name'] = $userData['User']['first_name'] . " " . $userData['User']['last_name'];
        if ($userData['User']['email'] != "") {
            $userData['Staff']['email'] = $userData['User']['email'];
        }
        if ($userData['User']['confirm_password'] != '') {
            $userData['Staff']['password'] = Security::hash($this->request->data['User']['pwd'], null, true);
        }
        if ($userData['User']['homephone'] != "") {
            $userData['Staff']['homephone'] = $userData['User']['homephone'];
        }
        if ($userData['User']['mobile'] != "") {
            $userData['Staff']['mobile'] = $userData['User']['mobile'];
        }
        $userData['Staff']['status'] = $userData['User']['active_status'];


        if ($staffModel->save($userData['Staff'])) {
            return true;
        } else {
            return false;
        }
    }

    /* __________________________________________________________
     * @Method      :mydashboard
     * @Description :to set up the staff dashboard section
     * @access      :null
     * @param      :null
     * @return     :null
     */

    function mydashboard() {

        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');
	$roleId = $this->Auth->User('role_id');
	
	if($roleId != 5 && $roleId != 6){
        
		App::Import("Model", "UserServiceUnit");
		$this->UserServiceUnit = new UserServiceUnit();
		$associatedServiceUnit = $this->UserServiceUnit->find('list', array(
					    'conditions' => array('UserServiceUnit.user_id' => $userId), 
					    'fields' => array('UserServiceUnit.service_unit_id'))
					);
		$associatedServiceUnit = array_unique($associatedServiceUnit);
		
		$associatedUserToUnit = $this->UserServiceUnit->find('list', array(
					    'conditions' => array('UserServiceUnit.service_unit_id' => $associatedServiceUnit, 'UserServiceUnit.user_id !=' => $userId), 
					    'fields' => array('UserServiceUnit.user_id'))
					);
		$associatedUserToUnit = array_unique($associatedUserToUnit);
		
		$this->User->recursive = -1;
		$conditions['User.id'] = $associatedUserToUnit;
		
		$associatedUsers = $this->paginate('User', array($conditions,'User.role_id !=' => 6,'User.role_id !=' => 5));
		$this->set('associatedUsers', $associatedUsers);
	}
        
        App::Import("Model", "UserMail");
        $this->UserMail = new UserMail();
        $this->UserMail->bindModel(array(
            'belongsTo' => array(
                'User' => array(
                    'foreignKey' => false,
                    'conditions' => 'Mail.sent_by = User.id'
                )
            )
        ), false);
        
        $oneWeekBackDate = date('Y-m-d', strtotime(date('Y-m-d') . " -7 days"));
        $associatedMail = $this->UserMail->find('all', array(
                                    'conditions' => array('UserMail.user_id' => $userId, 'UserMail.created >' => $oneWeekBackDate), 
                                    'fields' => array('UserMail.created', 'Mail.mail_type', 'Mail.id', 'User.e_name'),
                                    'limit' => 5,
                                    'order' => array('UserMail.id' => 'desc')
                                    )
                                );
        
        /*$userData = array();
        if(!empty($associatedMail)){
            foreach ($associatedMail as $fetcheddData){
               $usersIncluded[] =  $fetcheddData['Mail']['sent_by'];
            }
            $usersIncluded = array_unique($usersIncluded);
            $userData = $this->User->find('all', array(
                        'conditions' => array('User.id' => $usersIncluded),
                        'fields' => array('User.e_name', 'User.id')
                    ));
            foreach($userData as $fetcheUserData){
                $userData[$fetcheUserData['User']['id']] = $fetcheUserData['User']['e_name'];
            }
        }*/
        
        $this->set('associatedMail', $associatedMail);
        //$this->set('userData', $userData);
        
	
	App::Import("Model", "MessageBoard");
        $this->MessageBoard = new MessageBoard();
        $associatedMessageBoard = $this->MessageBoard->find('all', array(
                                        'conditions' => array('MessageBoard.chk1' => 1), 
                                        'limit' => 5,
                                        'order' => array('MessageBoard.mdate' => 'desc')
                                        )
                                    );
	
        $this->set('associatedMessageBoard', $associatedMessageBoard);
	
	
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('associated_users_list', 'ajax');
        }//if
    }

    /* __________________________________________________________
     * @Method      :postmain
     * @Description :To manage posts
     * @access      :null
     * @param      :null
     * @return     :null
     *  */

    function postmain() {

        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        $savecrit = '';

        //criteria array for search
        $crit = array();
        $crit[] = "";

        if (isset($this->request->data)) {

            if (isset($this->request->data['UserPost']['search_criteria']) && $this->request->data['UserPost']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->request->data['UserPost']['search_criteria']);
                //will search with name and abbreviation
                $crit[] = "(UserPost.post_name like '%" . $searchCriteriaTerm . "%')";
                $savecrit .= "search_criteria:" . $searchCriteriaTerm . "/";
            }
        }
        //for passing the values of search conditions in params of paging to next page
        if (count($this->params['named']) > 0) {
            foreach ($this->params['named'] as $paramKey => $paramValue) {
                $savecrit .= $paramKey . ":" . $paramValue . "/";
            }
            if (isset($this->params['named']['search_criteria']))
                $crit[] = "(UserPost.post_name like '%" . $this->params['named']['search_criteria'] . "%')";
        }//if
        if (count($crit) > 0) {
            $criteria = implode("1 AND ", $crit);
        } else {
            $criteria = "";
        }

        App::Import("Model", "UserPost");
        $this->UserPost = new UserPost();

        $postMainData = $this->paginate('UserPost', array($criteria));

        $this->set('postMainData', $postMainData);

        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('postmain', 'ajax');
        }//if
    }

    /**
     * @Method       :addpost
     * @Description  :to add User post
     * @access       :public
     * @param        :null
     * @return       :null
     */
    public function addpost() {


        $this->layout = 'home';

        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        if ($this->request->is('post')) {
            App::Import("Model", "UserPost");
            $this->UserPost = new UserPost();
            $this->UserPost->create();
            if ($this->UserPost->save($this->request->data)) {
                $msg = __("USER_POST_ADD_SUCCESS", true);
                $cls = "totalSuccess";

                $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');

                return $this->redirect(array('action' => 'postmain'));
            }
            $msg = __("USER_POST_ADD_FAILURE", true);
            $cls = "totalErrors";

            $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');
        }
    }

    /**
     * @Method       :editpost
     * @Description  :to edit user post
     * @access       :public
     * @param        :null
     * @return       :null
     */
    public function editpost($id = null) {
        $this->layout = 'home';

        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');


        if (!$id) {
            throw new NotFoundException(__('INVALID_SERVICE_GROUP'));
        }
        App::Import("Model", "UserPost");
        $this->UserPost = new UserPost();

        $userPost = $this->UserPost->findById($id);

        if (!$userPost) {
            throw new NotFoundException(__('INVALID_SERVICE_GROUP'));
        }
        if ($this->request->is(array('UserPost', 'put'))) {
            $this->UserPost->id = $id;
            if ($this->UserPost->save($this->request->data)) {
                $msg = __("USER_POST_UPDATE_SUCCESS", true);
                $cls = "totalSuccess";

                $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');

                return $this->redirect(array('action' => 'postmain'));
            }
            $msg = __("USER_POST_UPDATE_FAILURE", true);
            $cls = "totalErrors";

            $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');
        }
        if (!$this->request->data) {
            $this->request->data = $userPost;
        }
    }

    /* __________________________________________________________
     * @Method      :roles
     * @Description :To manage roles
     * @access      :null
     * @param      :null
     * @return     :null
     *  */

    function roles() {

        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        $savecrit = '';

        //criteria array for search
        $crit = array();
        $crit[] = "";

        if (isset($this->request->data)) {

            if (isset($this->request->data['Role']['search_criteria']) && $this->request->data['Role']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->request->data['Role']['search_criteria']);
                //will search with name and abbreviation
                $crit[] = "(Role.role_name like '%" . $searchCriteriaTerm . "%')";
                $savecrit .= "search_criteria:" . $searchCriteriaTerm . "/";
            }
        }
        //for passing the values of search conditions in params of paging to next page
        if (count($this->params['named']) > 0) {
            foreach ($this->params['named'] as $paramKey => $paramValue) {
                $savecrit .= $paramKey . ":" . $paramValue . "/";
            }
            if (isset($this->params['named']['search_criteria']))
                $crit[] = "(Role.role_name like '%" . $this->params['named']['search_criteria'] . "%')";
        }//if
        if (count($crit) > 0) {
            $criteria = implode("1 AND ", $crit);
        } else {
            $criteria = "";
        }

        App::Import("Model", "Role");
        $this->Role = new Role();

        $roleData = $this->paginate('Role', array($criteria));

        $this->set('roleData', $roleData);

        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('roles', 'ajax');
        }//if
    }

    /**
     * @Method       :addrole
     * @Description  :to add User role
     * @access       :public
     * @param        :null
     * @return       :null
     */
    public function addrole() {

        $this->layout = 'home';

        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        if ($this->request->is('post')) {
            App::Import("Model", "Role");
            $this->Role = new Role();
            $this->Role->create();
            if ($this->Role->save($this->request->data)) {
                $msg = __("USER_ROLE_ADD_SUCCESS", true);
                $cls = "totalSuccess";

                $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');

                return $this->redirect(array('action' => 'roles'));
            }
            $msg = __("USER_ROLE_ADD_FAILURE", true);
            $cls = "totalErrors";

            $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');
        }
    }

    /**
     * @Method       :editrole
     * @Description  :to edit user role
     * @access       :public
     * @param        :null
     * @return       :null
     */
    public function editrole($id = null) {
        $this->layout = 'home';

        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');


        if (!$id) {
            throw new NotFoundException(__('INVALID_SERVICE_GROUP'));
        }
        App::Import("Model", "Role");
        $this->Role = new Role();

        $userRole = $this->Role->findById($id);

        if (!$userRole) {
            throw new NotFoundException(__('INVALID_SERVICE_GROUP'));
        }
        if ($this->request->is(array('Role', 'put'))) {
            $this->Role->id = $id;
            if ($this->Role->save($this->request->data)) {
                $msg = __("USER_ROLE_UPDATE_SUCCESS", true);
                $cls = "totalSuccess";

                $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');

                return $this->redirect(array('action' => 'roles'));
            }
            $msg = __("USER_ROLE_UPDATE_FAILURE", true);
            $cls = "totalErrors";

            $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');
        }
        if (!$this->request->data) {
            $this->request->data = $userRole;
        }
    }

    /* __________________________________________________________
     * @Method      :showpermissions
     * @Description :Shows the permission of each role
     * @access      :null
     * @param      :roleID
     * @return     :null
     */

    function showpermissions($roleId) {

        if (!isset($roleId) or $roleId <= 0) {
            $this->redirect(array('controller' => 'users', 'action' => 'roles'));
        }
	
	App::Import("Model", "Role");
        $this->Role = new Role();
	
        $this->set('roleId', $roleId);

        $this->layout = 'home';

        $permissionArray = $this->SystemModule->find("all", array('fields' => 'group', 'conditions' => 'module_type = \'1\'', 'group' => 'SystemModule.group'));

        $this->set('permissionArray', $permissionArray);
    }

    /* __________________________________________________________
     * @Method      :showcategory
     * @Description :Shows the modules under main module
     * @access      :null
     * @param      :usertypeId
     * @return     :null
     */

    function showcategory($group = '', $roleId = '') {

        App::Import("Model", "SystemModule");
        $this->SystemModule = new SystemModule();

        $this->SystemModule->recursive = 1;
        $this->set('roleId', $roleId);

        $permissionArray = $this->SystemModule->find("all", array('conditions' => 'SystemModule.module_type = \'1\' and SystemModule.group = \'' . $group . '\'', 'order' => 'SystemModule.order ASC'));
        if ($this->request->is('ajax')) {
            $this->set('permissionArray', $permissionArray);
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('moduleview', 'ajax');
        }
    }

    /* __________________________________________________________
     * @Method      :showModulePermissions
     * @Description :Shows the permission of each usertypes
     * @access      :null
     * @param      :usertypeId
     * @return     :null
     */

    function showmodulepermission($moduleName = null, $roleId = '') {

        $this->set('roleId', $roleId);
        $this->set('moduleName', $moduleName);
        App::Import("Model", "SystemModulePermission");
        $this->SystemModulePermission = new SystemModulePermission();
	
	App::Import("Model", "Role");
        $this->Role = new Role();
	
	$roleArray = $this->Role->find("first", array('fields' => 'role_name', 'conditions' => 'id = '.$roleId));
	
	if(is_array($roleArray) && count($roleArray) > 0){
		$this->set('roleName', $roleArray['Role']['role_name']);
	}else{
		$this->redirect(array('controller' => 'users', 'action' => 'roles'));
	}

        $this->SystemModule->bindModel(
                array('hasMany' => array(
                        'SystemModulePermission' => array(
                            'className' => 'SystemModulePermission',
                            'foreignKey' => 'system_module_id',
                            'type' => 'INNER',
                            'conditions' => 'SystemModulePermission.role_id = ' . $roleId
                        )
                    )
                )
        );
        $this->SystemModule->recursive = 1;

        $permissionArray = $this->SystemModule->find("all", array('conditions' => 'SystemModule.module_unique_name = \'' . $moduleName . '\'', 'order' => 'SystemModule.order ASC'));
        $this->set('permissionArray', $permissionArray);
        
        if($moduleName == 'PART_TIME_PAYROLL'){
		$main_module_name_to_display = 'Work Flow';
		$module_name_to_display = 'Part time payroll';	
	}elseif($moduleName == 'PART_TIME_PAYROLL_ADMIN'){
		$main_module_name_to_display = 'Admin Control';
		$module_name_to_display = 'Part time payroll admin';	
	}elseif($moduleName == 'UNIT_MAINTENANCE'){
		$main_module_name_to_display = 'System Admin';
		$module_name_to_display = 'Unit Maintenance';	
	}elseif($moduleName == 'SERVICE_GROUPS'){
		$main_module_name_to_display = 'System Admin';
		$module_name_to_display = 'Service Groups';	
	}elseif($moduleName == 'POST_MAIN'){
		$main_module_name_to_display = 'System Admin';
		$module_name_to_display = 'Post Maintenance';	
	}elseif($moduleName == 'ROLES'){
		$main_module_name_to_display = 'System Admin';
		$module_name_to_display = 'Roles';	
	}elseif($moduleName == 'STAFF_MAINT'){
		$main_module_name_to_display = 'System Admin';
		$module_name_to_display = 'Staff Maintenance';	
	}elseif($moduleName == 'FINANCE_CONTROL'){
		$main_module_name_to_display = 'Finance Control';
		$module_name_to_display = 'Post Messages';	
	}else{
		$main_module_name_to_display = '';
		$module_name_to_display = '';	
	}
	
        $this->set('main_module_name_to_display', $main_module_name_to_display);
        $this->set('module_name_to_display', $module_name_to_display);
        
        $this->disableCache();
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('permissionView', 'ajax');
        }
    }

    /* __________________________________________________________
     * @Method      :updatepermission
     * @Description :For updating/changing the permission of
     * 		particular usertype
     * @access      :null
     * @param      :$action(The permission which have to be changed)
     * @param      :$id(permission id)
     * @param      :$usertypeID(To call the function again)
     * @return     :null
     */

    function updatepermission($moduleName, $action = null, $id = null, $roleID = null) {
        //Importing the model///////
        App::Import("Model", "SystemModulePermission");
        $this->SystemModulePermission = new SystemModulePermission();

        // check id is valid
        if ($id != null && is_numeric($id)) {
            if ($action == "allowperm") {
                $actionVal = 1;
                $this->request->data['SystemModulePermission']['id'] = $id;
            }
            //This is the case when permission to any new module is granted
            elseif ($action == "insertallowperm") {
                $this->SystemModulePermission->recursive = -1;
                $isModuleAlreadyExist = $this->SystemModulePermission->find("first", array('conditions' => array('SystemModulePermission.system_module_id' => $id, 'SystemModulePermission.role_id' => $roleID)));

                if (is_array($isModuleAlreadyExist) && count($isModuleAlreadyExist) > 0) {
                    $this->request->data['SystemModulePermission']['id'] = $isModuleAlreadyExist['SystemModulePermission']['id'];
                }
                $actionVal = 1;
                $this->request->data['SystemModulePermission']['system_module_id'] = $id;
                $this->request->data['SystemModulePermission']['role_id'] = $roleID;
                $this->request->data['SystemModulePermission']['staff_id'] = $this->Auth->User("id");
            } else {
                $actionVal = 0;
                $this->request->data['SystemModulePermission']['id'] = $id;
            }

            $this->request->data['SystemModulePermission']['permission'] = $actionVal;
            if ($this->SystemModulePermission->save($this->request->data['SystemModulePermission'])) {
		
                if ($actionVal == 1) {
                    $msg = __('PERMISSION_GRANTED_SUCCEESSFULLY', true);
                    $class = 'totalSuccess';
                } else {
                    $msg = __('PERMISSION_DENIED_SUCCEESSFULLY', true);
                    $class = 'totalSuccess';
                }
            } else {
                $msg = __('CANNOT_PERFORM', true);
                $class = 'totalErrors';
            }
            $this->Session->setFlash('<div class=' . $class . '>' . $msg . '</div>');
        }

        if ($this->request->is('ajax')) {
            $this->showmodulepermission($moduleName, $roleID);
        }
    }

    /* __________________________________________________________
     * @Method      :updatemultiplemodulepermission
     * @Description :For updating/changing the permission of
     * 		particular usertype for multiple module id's
     * @access      :null
     * @param      :$action(The permission which have to be changed)
     * @return     :null
     */

    function updatemultiplemodulepermission($action = null) {
        //Importing the model///////
        $this->disableCache();
        App::Import("Model", "SystemModulePermission");
        $this->SystemModulePermission = new SystemModulePermission();
        if (isset($this->params['data']['systemids']) && count($this->params['data']['systemids']) > 0) {
            foreach ($this->params['data']['systemids'] as $systemIdarray) {

                $systemIds = explode("/", $systemIdarray);

                //This is the case when permission to any new module is granted
                if ($systemIds[0] == "insertallowperm") {
                    $this->SystemModulePermission->recursive = -1;
                    $isModuleAlreadyExist = $this->SystemModulePermission->find("first", array('conditions' => array('SystemModulePermission.system_module_id' => $systemIds[1], 'SystemModulePermission.role_id' => $systemIds[2])));

                    if (is_array($isModuleAlreadyExist) && count($isModuleAlreadyExist) > 0) {
                        $this->request->data['SystemModulePermission']['id'] = $isModuleAlreadyExist['SystemModulePermission']['id'];
                    }
                    $this->request->data['SystemModulePermission']['system_module_id'] = $systemIds[1];
                    $this->request->data['SystemModulePermission']['role_id'] = $systemIds[2];
                    $this->request->data['SystemModulePermission']['staff_id'] = $this->Auth->User("id");
                    if ($action == "allow") {
                        $this->request->data['SystemModulePermission']['permission'] = 1;
                    } else {
                        $this->request->data['SystemModulePermission']['permission'] = 0;
                    }
                } elseif ($action == "allow") {
                    $this->request->data['SystemModulePermission']['id'] = $systemIds[1];
                    $this->request->data['SystemModulePermission']['permission'] = 1;
                } elseif ($action == "deny") {
                    $this->request->data['SystemModulePermission']['id'] = $systemIds[1];
                    $this->request->data['SystemModulePermission']['permission'] = 0;
                }

                $this->SystemModulePermission->save($this->request->data['SystemModulePermission']);
                $this->SystemModulePermission->id = "";
            }

            $class = 'totalSuccess';
            $msg = __('PERMISSION_CHANGED_SUCCESSFULLY', true);
            $this->Session->setFlash('<div class=' . $class . '>' . $msg . '</div>');
            $this->redirect('/users/showpermissions/' . $systemIds[2]);
        } else {
            $class = 'totalErrors';
            $msg = __('PERMISSION_CHANGED_FAILED', true);
            $this->Session->setFlash('<div class=' . $class . '>' . $msg . '</div>');
            $this->redirect('/users/roles');
        }
    }

    /* __________________________________________________________
     * @Method      :staffmain
     * @Description :Manage staff
     * @access      :null
     * @param      :null
     * @return     :null
     */

    function staffmain() {

        $this->layout = 'home';
        $savecrit = '';
        //criteria array for search
        $crit = array();
        $crit[] = "(User.user_type != 1 AND User.is_delete != 1)";

        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        $this->User->recursive = 2;

        //Save log of the user history
        App::Import("Model", "UserLog");
        $staffModel = new UserLog();

        $userLogArr['user_id'] = $userId;
        $userLogArr['type'] = 'staff';
        $userLogArr['description'] = 'Accessed Staff management at ' . date("Y-m-d H:i:s");

        $staffModel->save($userLogArr);
        //End Save log of the user history

        if (isset($this->request->data)) {

            if (isset($this->request->data['User']['search_criteria']) && $this->request->data['User']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->request->data['User']['search_criteria']);
                //will search with first name and email and last name
                $crit[] = "(User.e_name like '%" . $searchCriteriaTerm . "%'" . " OR User.c_name like '%" . $searchCriteriaTerm . "%'" . " OR User.email like '%" . $searchCriteriaTerm . "%')";
                $savecrit .= "search_criteria:" . $searchCriteriaTerm . "/";
            }
        }
        //for passing the values of search conditions in params of paging to next page
        if (count($this->params['named']) > 0) {
            foreach ($this->params['named'] as $paramsKey => $paramsValue) {
                $savecrit .= $paramsKey . ":" . $paramsValue . "/";
            }
            if (isset($this->params['named']['search_criteria']))
                $crit[] = "(User.e_name like '%" . $this->params['named']['search_criteria'] . "%'" . " User.c_name like '%" . $this->params['named']['search_criteria'] . "%'" . " OR User.email like '%" . $this->params['named']['search_criteria'] . "%')";
        }//if
	
        if (count($crit) > 0) {
            $criteria = implode(" AND ", $crit);
        } else {
            $criteria = "";
        }

        $staffDetailarray = $this->paginate('User', array($criteria));

        $this->set('staffDetailarray', $staffDetailarray);
        $this->set('userType', $userType);


        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('viewstaff', 'ajax');
        }
    }

    /* __________________________________________________________
     * @Method      :createstaff
     * @Description :to create staff members
     * @access      :null
     * @param      :null
     * @return     :null
     */

    function createstaff() {

        $this->layout = 'home';

        //Importing the model
        App::Import("Model", "Role");
        $this->Role = new Role();

        $userRoleArray = $this->Role->find("all");

        $userRoleList = Set::combine($userRoleArray, '{n}.Role.id', '{n}.Role.role_name');
        $this->set("userRoleList", $userRoleList); // 	array to set all usertypes with id to show in drop down

        /*App::Import("Model", "ServiceGroup");
        $this->ServiceGroup = new ServiceGroup();
        $serviceGroup = $this->ServiceGroup->find('list', array('fields' => array('ServiceGroup.id', 'ServiceGroup.group_name')));
        $this->set("serviceGroup", $serviceGroup);*/

        //Importing the model
        /*App::Import("Model", "ServiceUnit");
        $this->ServiceUnit = new ServiceUnit();
        $serviceUnitArray = $this->ServiceUnit->find("all");
        $serviceUnitList = Set::combine($serviceUnitArray, '{n}.ServiceUnit.id', '{n}.ServiceUnit.unit_name');
        $this->set("serviceUnitList", $serviceUnitList); // 	array to set all usertypes with id to show in drop down*/


        if ($this->request->is('post')) {
            $this->User->set($this->request->data);
            //validation from model
            
            if ($this->User->validates()) {
                //check the uniqueness of username
                if (!$this->User->isUnique('username', $this->request->data['User']['username'], '')) {
                    $err['username_exist'] = __('USERNAME_ALREADY_EXIST', true);
                }

                //check the uniqueness of email
                if (!$this->User->isUnique('email', $this->request->data['User']['email'], '')) {
                    $err['email'] = __('EMAIL_ALREADY_EXIST', true);
                }

                if (!isset($err) || count($err) == 0) {

                    //$this->request->data['User']['password'] = Security::hash($this->request->data['User']['password'], null, true);
                    //staff id will be logged in id who have added the usertype

                    $this->User->save($this->request->data['User']);

                    $staffId = $this->User->getLastInsertId();
                    
                    /*App::Import("Model", "UserServiceUnit");
                    $this->UserServiceUnit = new UserServiceUnit();
                    $userServiceUnit = array();
                    foreach($this->request->data['User']['service_unit_id'] as $unitIds){
                        $userServiceUnit[]['UserServiceUnit'] =array(
                            'user_id' => $staffId,
                            'service_unit_id' => $unitIds
                        );
                    }
                    
                    $this->UserServiceUnit->saveMany($userServiceUnit);*/
                    
                    $this->saveActionLog('staff', 'Staff Added ID :'. $staffId);
                    
                    $msg = __("STAFF_ADDED", true);
                    $this->Session->setFlash('<div class = "totalSuccess">' . $msg . '</div>');

                    $this->redirect('/users/staffmain');
                } else {
                    $msg = __("STAFF_ADDED_FAILED", true);
                    foreach ($err as $errord) {
                        $msg .= "<br>" . $errord;
                    }
                    $this->Session->setFlash('<div class = "totalErrors">' . $msg . '</div>');
                }
            } else {
                $errors = $this->User->validationErrors;
                $this->set("errors", $errors);
            }
        }
    }
    
    /*__________________________________________________________
    * @Method      :get_service_unit
    * @Description :to get service unit on ajax requet
    * @access      :null
    * @param      :null
    * @return     :null
    */
    public function get_service_unit() {

        $this->layout = '';
        App::Import("Model", "ServiceUnit");
        $this->ServiceUnit = new ServiceUnit();

        $serviceUnitList = $this->ServiceUnit->find('list', array(
            'conditions' => array('ServiceUnit.service_group_id' => $this->request->data['User']['service_group_id']),
            'fields' => array('ServiceUnit.id', 'ServiceUnit.unit_name')
        ));
        $this->set("serviceUnitList", $serviceUnitList);
    }
    
    /*__________________________________________________________
    * @Method      :updatestaff
    * @Description :to update staff
    * @access      :null
    * @param      :null
    * @return     :null
    */
    public function updatestaff($id = null) {
        
        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        $this->User->recursive = 2;

        App::Import("Model", "Role");
        $this->Role = new Role();
        $userRoleArray = $this->Role->find("all");

        $userRoleList = Set::combine($userRoleArray, '{n}.Role.id', '{n}.Role.role_name');
        $this->set("userRoleList", $userRoleList); // 	array to set all usertypes with id to show in drop down

        App::Import("Model", "ServiceGroup");
        $this->ServiceGroup = new ServiceGroup();
        $serviceGroup = $this->ServiceGroup->find('list', array('fields' => array('ServiceGroup.id', 'ServiceGroup.group_name')));
        $this->set("serviceGroup", $serviceGroup);

        //Importing the model
        /*App::Import("Model", "ServiceUnit");
        $this->ServiceUnit = new ServiceUnit();
        $serviceUnitArray = $this->ServiceUnit->find("all");
        $serviceUnitList = Set::combine($serviceUnitArray, '{n}.ServiceUnit.id', '{n}.ServiceUnit.unit_name');
        $this->set("serviceUnitList", $serviceUnitList); // 	array to set all usertypes with id to show in drop down*/
        
        if (!$id) {
            throw new NotFoundException(__('INVALID_STAFF'));
        }
        $user = $this->User->findById($id);
        //pr($user);
        /*$userServiceUnit = array();
        if(isset($user['UserServiceUnit'])){
            foreach($user['UserServiceUnit'] as $unitList){
                $userServiceUnit[] = $unitList['service_unit_id'];
            }
        }
        $user['User']['service_unit_id'] = $userServiceUnit;//$user['User']['ServiceGroup']['id'];*/

        if (!$user) {
            throw new NotFoundException(__('INVALID_STAFF'));
        }
	
        if ($this->request->is(array('User', 'put'))) {
            $this->User->id = $id;
	    $newPwd = trim($this->request->data['User']['pwd']);
	    if(!empty($newPwd)){
		$this->request->data['User']['password'] = $this->request->data['User']['pwd'];
	    }
	    
	    if(!isset($this->request->data['User']['on_leave'])){
		$this->request->data['User']['on_leave'] = 0;
                }
                
            if ($this->User->save($this->request->data)) {

                $msg = __("USER_UPDATE_SUCCESS", true);
                $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                return $this->redirect(array('action' => 'staffmain'));
            }
	    $msg = __("USER_UPDATE_FAILURE", true);
	    $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
        }
	
        if (!$this->request->data) {
            $this->request->data = $user;
        }
    }
    
    /* __________________________________________________________
     * @Method      :parttimepayrolladmin
     * @Description :to show part time payroll in admin control section
     * @access      :null
     * @param      :null
     * @return     :null
     */

    function postmessageadmin() {

        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');
    }
    
    /* __________________________________________________________
     * @Method      :postmessagefinance
     * @Description :to show part post message in finance section
     * @access      :null
     * @param      :null
     * @return     :null
     */

    function postmessagefinance() {

        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');
    }
    
    /* __________________________________________________________
     * @Method      :unit_permission
     * @Description :to update unit allocated to user
     * @access      :null
     * @param      :$userid
     * @return     :null
     */
    public function change_unit_permission($user_id  = null) {
        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');
        
        if (!$user_id) {
            throw new NotFoundException(__('INVALID_STAFF'));
        }
	
	$userPermissions = $this->User->findById($user_id);

	$lang = Configure::read('Config.language');
	if ($lang == 'eng') {
            $user_name = $userPermissions['User']['e_name'];
        } else {
            $user_name = $userPermissions['User']['c_name'];
        }
	
	$savecrit = '';
        //criteria array for search
        $crit = array();
	
	if (isset($this->request->data)) {

            if (isset($this->request->data['User']['search_criteria']) && $this->request->data['User']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->request->data['User']['search_criteria']);
                //will search with first name and email and last name
                $crit[] = "(ServiceUnit.unit_name like '%" . $searchCriteriaTerm . "%'" . " OR ServiceUnit.unit_code like '%" . $searchCriteriaTerm . "%')";
                $savecrit .= "search_criteria:" . $searchCriteriaTerm . "/";
            }
        }
        //for passing the values of search conditions in params of paging to next page
        if (count($this->params['named']) > 0) {
            foreach ($this->params['named'] as $paramsKey => $paramsValue) {
                $savecrit .= $paramsKey . ":" . $paramsValue . "/";
            }
            if (isset($this->params['named']['search_criteria']))
                $crit[] = "(ServiceUnit.unit_name like '%" . $this->params['named']['search_criteria'] . "%'" . " ServiceUnit.unit_code like '%" . $this->params['named']['search_criteria'] . "%')";
        }//if
	
        if (count($crit) > 0) {
            $criteria = implode(" AND ", $crit);
        } else {
            $criteria = "";
        }
        
        App::Import("Model", "ServiceUnit");
        $this->ServiceUnit = new ServiceUnit();
        
        $serviceUnitList = $this->paginate('ServiceUnit', array($criteria));
        $this->set('serviceUnitList', $serviceUnitList);

        App::Import("Model", "UserServiceUnit");
        $this->UserServiceUnit = new UserServiceUnit();

        $allocatedUnitList = $this->UserServiceUnit->find('list', array(
                            'conditions' => array('UserServiceUnit.user_id' =>$user_id),
                            'fields' => array('UserServiceUnit.id', 'UserServiceUnit.service_unit_id')));
        $this->set('allocatedUnitList', $allocatedUnitList);
        $this->set('user_id', $user_id);
	$this->set('user_name', $user_name);
        
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('unit_list', 'ajax');
        }
        
        
        if ($this->request->is(array('User', 'put'))) {
            $this->User->id = $id;
	    $newPwd = trim($this->request->data['User']['pwd']);
	    if(!empty($newPwd)){
		$this->request->data['User']['password'] = $this->request->data['User']['pwd'];
	    }
	    
            if ($this->User->save($this->request->data)) {
                App::Import("Model", "UserServiceUnit");
                $this->UserServiceUnit = new UserServiceUnit();
                
                $previousUnitList = $this->UserServiceUnit->find('list', array(
                                    'conditions' => array('UserServiceUnit.user_id' => $this->User->id),
                                    'fields' => array('UserServiceUnit.id')));
                
                if(count($previousUnitList)){
                    $condition = array('UserServiceUnit.id' => $previousUnitList);
                    $this->UserServiceUnit->deleteAll($condition, FALSE);
                }
                $userServiceUnit = array();
                foreach ($this->request->data['User']['service_unit_id'] as $unitIds) {
                    $userServiceUnit[]['UserServiceUnit'] = array(
                        'user_id' => $this->User->id,
                        'service_unit_id' => $unitIds
                    );
                }
                
                $this->UserServiceUnit->saveMany($userServiceUnit);

                $msg = __("USER_UPDATE_SUCCESS", true);
                $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                return $this->redirect(array('action' => 'staffmain'));
            }
	    $msg = __("USER_UPDATE_FAILURE", true);
	    $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
        }
    }
    
    
    /* __________________________________________________________
     * @Method      :allow_unit
     * @Description :to update unit allocated to user
     * @access      :null
     * @param      :$user_id
     * @return     :null
     */
    public function allow_unit($user_id  = null, $service_unit_id = null, $pageNo = null, $limit = null) {
        $this->disableCache();
        $userId   = $this->Auth->User("id");
	$userType = $this->Auth->User('user_type');
        $this->autoRender = false;
        $this->layout = '';
        
        App::Import("Model", "ServiceUnit");
        $this->ServiceUnit = new ServiceUnit();

        //$this->paginate = array('page' => $pageNo);
	if(isset($limit) && $limit > 0){
            $this->paginate = array('limit' => intval($limit), 'page' => $pageNo);
        } else{
            $this->paginate = array('limit' => 25, 'page' => $pageNo);
        }
	
        $serviceUnitList = $this->paginate('ServiceUnit');
	
        $this->set('serviceUnitList', $serviceUnitList);
        
        App::Import("Model", "UserServiceUnit");
        $this->UserServiceUnit = new UserServiceUnit();
                
        $userServiceUnit['UserServiceUnit'] = array(
            'user_id' => $user_id,
            'service_unit_id' => $service_unit_id
        );
                
        $this->UserServiceUnit->save($userServiceUnit);
        
        $allocatedUnitList = $this->UserServiceUnit->find('list', array(
                            'conditions' => array('UserServiceUnit.user_id' =>$user_id),
                            'fields' => array('UserServiceUnit.service_unit_id')));
        $this->set('allocatedUnitList', $allocatedUnitList);
        $this->set('user_id', $user_id);
        
        $msg = __("SERVICE_UNIT_UPDATE_SUCCESS", true);
        $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                
        //pr($allocatedUnitList);
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('unit_list', 'ajax');
        }
    }
    
    /* __________________________________________________________
     * @Method      :allow_unit
     * @Description :to update unit allocated to user
     * @access      :null
     * @param      :$user_id
     * @return     :null
     */
    public function revoke_unit($user_id  = null, $user_service_unit_id = null, $pageNo = null, $limit = null) {
        $this->disableCache();
        $userId   = $this->Auth->User("id");
	$userType = $this->Auth->User('user_type');
        $this->autoRender = false;
        $this->layout = '';
        
        App::Import("Model", "ServiceUnit");
        $this->ServiceUnit = new ServiceUnit();
	
	
	if(isset($limit) && $limit > 0){
            $this->paginate = array('limit' => intval($limit), 'page' => $pageNo);
        } else{
            $this->paginate = array('limit' => 25, 'page' => $pageNo);
        }
	
        $serviceUnitList = $this->paginate('ServiceUnit');
	
        $this->set('serviceUnitList', $serviceUnitList);
        
        App::Import("Model", "UserServiceUnit");
        $this->UserServiceUnit = new UserServiceUnit();
        $this->UserServiceUnit->delete($user_service_unit_id);
        
        $allocatedUnitList = $this->UserServiceUnit->find('list', array(
                            'conditions' => array('UserServiceUnit.user_id' =>$user_id),
                            'fields' => array('UserServiceUnit.service_unit_id')));
        $this->set('allocatedUnitList', $allocatedUnitList);
        $this->set('user_id', $user_id);
        
        $msg = __("SERVICE_UNIT_UPDATE_SUCCESS", true);
        $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                
        //pr($allocatedUnitList);
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('unit_list', 'ajax');
        }
    }
    
    /*__________________________________________________________
    * @Method      :myaccount
    * @Description :to update own account
    * @access      :null
    * @param      :null
    * @return     :null
    */
    public function myaccount() {
        
        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');


        $user = $this->User->findById($userId);
        
        if (!$user) {
            throw new NotFoundException(__('INVALID_STAFF'));
        }
	
        if ($this->request->is(array('User', 'put'))) {
            $this->User->id = $userId;
	    $newPwd = trim($this->request->data['User']['pwd']);
	    if(!empty($newPwd)){
		$this->request->data['User']['password'] = $this->request->data['User']['pwd'];
	    }
	    
	    if(!$userType){
		if(!isset($this->request->data['User']['on_leave'])){
			$this->request->data['User']['on_leave'] = 0;
		    }
	    }
	    
            if ($this->User->save($this->request->data)) {

                $msg = __("USER_UPDATE_SUCCESS", true);
                $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                return $this->redirect(array('action' => 'myaccount'));
            }
	    $msg = __("USER_UPDATE_FAILURE", true);
	    $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
        }
	
	$this->set('userType', $userType);
	
        if (!$this->request->data) {
            $this->request->data = $user;
        }
    }
    
    /*__________________________________________________________
    * @Method      :myaccount
    * @Description :to update own account
    * @access      :null
    * @param      :null
    * @return     :null
    */
    public function delete($user_id = null){
        $userId   = $this->Auth->User("id");
	$userType = $this->Auth->User('user_type');
        $this->autoRender = false;
        $this->layout = '';
        
        $msg = '';
        if (!$user_id) {
            $msg = __("INVALID_USER", true);
            $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
            return $this->redirect(array('action' => 'staffmain'));
        }
        $user = $this->User->findById($user_id);

        if (!$user) {
            $msg = __("USER_NO_EXIST", true);
            $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
            return $this->redirect(array('action' => 'staffmain'));
        } else{
            //--- delete User---------
            App::Import("Model", "UserServiceUnit");
            $this->UserServiceUnit = new UserServiceUnit();
            $associatedServiceUnit = $this->UserServiceUnit->find('list', array(
                                        'conditions' => array('UserServiceUnit.user_id' => $user_id), 
                                        'fields' => array('UserServiceUnit.id'))
                                    );
            if(empty($associatedServiceUnit)){
                $this->User->validator()->remove('email');
                $userData['User'] = array(
                                    'id' => $user_id,
                                    'is_delete' => 1,
                                );
                $this->User->save($userData);

                $this->saveActionLog('staff', 'Staff Deleted ID :'. $user_id);
                $msg = __("USER_DELETE_SUCCESS", true);
                $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
            } else{
                $loginFailedMsg = __("CANNOT_DELETE_USER_ASSOCIATED_TO_SERVICE_UNIT", true);
                $this->Session->setFlash('<div class="totalErrors">' . $loginFailedMsg . '</div>');
            }
            return $this->redirect(array('action' => 'staffmain'));
        }
    }
    
    /* __________________________________________________________
     * @Method      :msgboardmain
     * @Description :To manage posts
     * @access      :null
     * @param      :null
     * @return     :null
     *  */

    function msgboardmain() {

        $this->layout = 'home';
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        App::Import("Model", "MessageBoard");
        $this->MessageBoard = new MessageBoard();

        $msgBoardMainData = $this->paginate('MessageBoard');

        $this->set('msgBoardMainData', $msgBoardMainData);

        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'users';
            $this->render('msgboardmain', 'ajax');
        }//if
    }
    
    
    /**
     * @Method       :addmsgboard
     * @Description  :to add message to board
     * @access       :public
     * @param        :null
     * @return       :null
     */
    public function addmsgboard() {


        $this->layout = 'home';

        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        if ($this->request->is('post')) {
            App::Import("Model", "MessageBoard");
            $this->MessageBoard = new MessageBoard();
            $this->MessageBoard->create();
            if ($this->MessageBoard->save($this->request->data)) {
                $msg = __("MESSAGE_ADD_SUCCESS", true);
                $cls = "totalSuccess";

                $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');

                return $this->redirect(array('action' => 'msgboardmain'));
            }
            $msg = __("MESSAGE_ADD_FAILURE", true);
            $cls = "totalErrors";

            $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');
        }
    }

    /**
     * @Method       :editmsgboard
     * @Description  :to edit message
     * @access       :public
     * @param        :null
     * @return       :null
     */
    public function editmsgboard($id = null) {
        $this->layout = 'home';

        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');


        if (!$id) {
            throw new NotFoundException(__('INVALID_SERVICE_GROUP'));
        }
        App::Import("Model", "MessageBoard");
        $this->MessageBoard = new MessageBoard();

        $msgBoard = $this->MessageBoard->findById($id);

        if (!$msgBoard) {
            throw new NotFoundException(__('INVALID_SERVICE_GROUP'));
        }
        if ($this->request->is(array('MessageBoard', 'put'))) {
            $this->MessageBoard->id = $id;
            if ($this->MessageBoard->save($this->request->data)) {
                $msg = __("MESSAGE_UPDATE_SUCCESS", true);
                $cls = "totalSuccess";

                $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');

                return $this->redirect(array('action' => 'msgboardmain'));
            }
            $msg = __("MESSAGE_UPDATE_FAILURE", true);
            $cls = "totalErrors";

            $this->Session->setFlash('<div class=' . $cls . '>' . $msg . '</div>');
        }
        if (!$this->request->data) {
            $this->request->data = $msgBoard;
        }
    }
}
